package com.farm.wcp.util;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;

import com.farm.iproject.domain.Dictype;

public class BootstrapTreeViews {
	private static final Logger log = Logger.getLogger(BootstrapTreeViews.class);

	/**
	 * 构造树控件的数据对象
	 * 
	 * @param types          原始分类集合
	 * @param isShowNum      是否显示课程数量（真实数量）
	 * @param isDoSum        是否进行数量合计
	 * @param isHideZeroNode 是否隐藏零数量的节点
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static List<Map<String, Object>> initData(List<Dictype> types, boolean isShowNum, boolean isDoSum,
			boolean isHideZeroNode) {
		Collections.sort(types, new Comparator<Dictype>() {
			@Override
			public int compare(Dictype o1, Dictype o2) {
				int n = o1.getTreecode().length() - o2.getTreecode().length();
				if (n == 0) {
					return o1.getSort() - o2.getSort();
				} else {
					return n;
				}
			}
		});
		List<Map<String, Object>> treeData = new ArrayList<>();
		Map<String, Map<String, Object>> treeDataMap = new HashMap<>();
		for (Dictype type : types) {
			Map<String, Object> node = null;
			// 构造当前节点
			if (treeDataMap.get(type.getId()) == null) {
				node = new HashMap<>();
				// 1结构，3内容
				String text = type.getName();
				node.put("text", text);
				node.put("name", type.getName());
				node.put("num", type.getNum());
				node.put("id", type.getId());
				treeDataMap.put(type.getId(), node);
			} else {
				node = (Map<String, Object>) treeDataMap.get(type.getId());
			}
			// ---------------------------
			// 挂载当前节点到数据结构中
			if (type.getParentid().equals("NONE")) {
				// 根节点
				treeData.add(node);
			} else {
				// 非根节点
				String parentid = type.getParentid();
				Map<String, Object> parentNode = (Map<String, Object>) treeDataMap.get(parentid);
				if (parentNode != null) {
					@SuppressWarnings("unchecked")
					List<Map<String, Object>> nodes = (List<Map<String, Object>>) parentNode.get("nodes");
					if (nodes == null) {
						// 没有子节点则构造子节点序列
						nodes = new ArrayList<>();
						parentNode.put("nodes", nodes);
					}
					nodes.add(node);
				} else {
					log.warn("父机构为空，可能是组织机构中有父机构为禁用状态");
				}
			}
		}
		// 重新计算分类下课程数量
		for (Map<String, Object> node : treeData) {
			long num = 0;
			if (isDoSum) {
				// 递归合计（数合计）
				num = countNums(node, isDoSum);
			} else {
				// 只合计下一层(数不合计)
				for (Map<String, Object> sub : (List<Map<String, Object>>) node.get("nodes")) {
					num = num + (long) sub.get("num");
				}
			}
			node.put("num", num);
			if (isShowNum && num > 0) {
				node.put("text", "<b>" + node.get("text") + "</b>");
			}
			// 显示数量
			showNumHtml(node, isShowNum);
		}
		if (isHideZeroNode) {
			treeData = hideZeroNode(treeData);
		}
		return treeData;
	}

	/**
	 * 隐藏删除零数量节点
	 * 
	 * @param treeData
	 * @return
	 */
	private static List<Map<String, Object>> hideZeroNode(List<Map<String, Object>> treeData) {
		Iterator<Map<String, Object>> it = treeData.iterator();
		while (it.hasNext()) {
			Map<String, Object> node = it.next();
			@SuppressWarnings("unchecked")
			List<Map<String, Object>> nodes = (List<Map<String, Object>>) node.get("nodes");
			if (nodes != null) {
				nodes = hideZeroNode(nodes);
			}
			if ((Long) node.get("num") <= 0) {
				it.remove();
			}
		}
		return treeData;
	}

	/**
	 * 显示数量
	 * 
	 * @param node
	 * @param isShowNum
	 */
	@SuppressWarnings("unchecked")
	private static void showNumHtml(Map<String, Object> node, boolean isShowNum) {
		if (isShowNum && node.get("num") != null && (long) node.get("num") > 0) {
			node.put("text", node.get("text") + "<span class=\\\"treeNum\\\" >" + node.get("num") + "<span>");
		}
		if (node.get("nodes") != null) {
			for (Map<String, Object> sub : (List<Map<String, Object>>) node.get("nodes")) {
				showNumHtml(sub, isShowNum);
			}
		}
	}

	/**
	 * 处理节点数量展示(父节点数量从字节点合并计算得出)
	 * 
	 * @param node
	 * @return
	 */
	private static long countNums(Map<String, Object> node, boolean isShowNum) {
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> subNodes = (List) node.get("nodes");
		long allnum = 0;
		if (subNodes == null) {
			subNodes = new ArrayList<Map<String, Object>>();
		}
		// 有子分類
		for (Map<String, Object> subnode : subNodes) {
			allnum = allnum + countNums(subnode, isShowNum);
		}
		allnum = allnum + (long) node.get("num");
		if (isShowNum && allnum > 0) {
			// node.put("text", node.get("text") + "<span class='wlp-type-falg'>" + allnum +
			// "<span>");
			node.put("num", allnum);
		}
		return allnum;
	}

	/**
	 * 是否有数量
	 * 
	 * @param treedata
	 * @return
	 */
	public static boolean isHasNum(List<Map<String, Object>> treedata) {
		for (Map<String, Object> node : treedata) {
			long num = (long) node.get("num");
			if (num > 0) {
				return true;
			}
		}
		return false;
	}
}
